<template>
	<div class="shop">
		<div class="header-bar" v-show="false">
			<div class="iconfont" @click="backPrvePage">&#xe624;</div>
			选择店铺
		</div>
		
		<div class="content" ref="shops" id="shop-content">
			<ul>
				<div class="header">
					<div class="address" @click="handleCityShow">{{cityName}} <span style="font-size: .24rem;" class="iconfont">&#xe779;</span></div>
					<div class="ipt-warrp">
						<div class="iconfont">&#xe60b;</div>
						<form action="" @submit="submitKey">							
							<input type="search"  @keyup.enter="submitKey" v-model.trim="keyword" placeholder="搜索商铺或者地点"  />
						</form>
						
					</div>
				</div>
				<li class="content-item vux-1px-b" v-for="(item,index) in storeList" :key="index">
					<div class="img-warrp">
						<img class="item-img" :src="item.frontImg+'?x-oss-process=style/w160h160'" alt="" />
					</div>
					<div class="item-info">
						<h4 class="item-title">{{item.name}}</h4>
						<p class="desc">{{item.address}}</p>
					</div>
					<div class="item-btn" v-if="isShare == 0">
						<div v-show="item.isClaim === false">
							<div class="btn" @click="goClaim(item)">{{btnStatus}}</div>
							<div class="distance">{{item.juli | juli}}</div>
						</div>
						<!--<div v-show="claimStatus == item.id">
							<div class="btn">审核中</div>
							<div class="distance">{{item.juli | juli}}</div>
						</div>-->
						<div class="claim-ok" v-show="item.isClaim === true">
							已认领
						</div>
					</div>
					<div class="item-btn" v-if="isShare == 1">
						<div class="btn" @click="goClaim(item)">详情</div>
					</div>
				</li>
				<div class="bottom-bar" v-show="moreData">{{dataInfo}}</div>
				<div class="no-store" v-show="noStore">
					<div class="no-img"><img height="100%" width="100%" src="../../../assets/images/functions/panda-sorry.png" alt="" /></div>
					<p class="desc">没有查找到该店铺，你可以选择自主创建店铺</p>
					<div class="btn" @click="toCreate">创建店铺</div>
				</div>
			</ul>
		</div>
		<city-list :cityList="cityList" v-show="cityShow" @closet="closeCityT" @close="closeCity" ref="children"></city-list>
		<transition name="fade">
			<login @close="closeDailog" :param="param" v-show="isLogin"></login>
		</transition>
	</div>
</template>

<script>
	import Bus from '../bus.js'
	import Login from '@/page/coinShop/login'
	import { setCookie, getCookie, removeCookie, clearCookie } from '@/assets/js/cookie'
	import {getUrlParam}  from '@/assets/js/getUrlParam'
	import Bscroll from "better-scroll"
	import CityList from "./components/cityList"
	export default{
		name : "shop",
		data(){
			return{
				isWeChat : true, 
				cityShow : false,
				page     : 1,
				storeList: [],
				cityList : {},
				dataInfo : '上拉加载更多',
				keyword  : '',
				timer    : null,
				cityId   : '',
				cityName : '',
				noStore  : false,
				tag      : false,
				hasPage  : false,
				locations: {},
				param    : '',
				isLogin  : false,
				btnStatus: '认领',
				isShare  : 0
			}
		},
		methods:{
			getLongitude(){
				let _this = this
//				this.$axiosPostn('/wechat/joins/sharetoken/10000.json',{
//					url:location.href.split('#')[0],
//					from:2
//				}).then( res => {			
//					wx.config({
//			            beta: true,
//			            debug: false,
//			            appId: res.appId,
//			            timestamp: res.timestamp,
//			            nonceStr: res.nonceStr,
//			            signature: res.signature,
//			            jsApiList: [
//							'checkJsApi',
//							'openLocation',
//							'getLocation',
//							'hideMenuItems',
//							'hideOptionMenu',
//							'showOptionMenu',
//							'closeWindow',
//							'onMenuShareTimeline',
//							'onMenuShareAppMessage',
//							'onMenuShareQQ',
//							'onMenuShareWeibo',
//							'onMenuShareQZone'
//          			]
//      			});
//				})
				this.$wxConfig('/wechat/joins/sharetoken/10000.json')
				wx.ready(function () {
					wx.getLocation({
					type: 'wgs84',
					success: function (res) {
						_this.locations.latitude = res.latitude; 
						_this.locations.longitude = res.longitude;
						_this.getShopList(1,getCookie('cityid'))
					}
					});
				}); 
				
			},
			closeDailog(){
				this.isLogin = false
			},
			urlParams(){
				let urlInfo = {
					uid   : getUrlParam('uid')   || getCookie('uid'),
					token : getUrlParam('token') || getCookie('token')
				}
				if(!this.isWeChat){
					if(!urlInfo.uid || !urlInfo.token){
						this.isLogin = true
						return false
					}
				}
				return urlInfo
			},
			backPrvePage(){
				if(this.keyword){
					this.keyword = ''
					window.location.reload()
					return
				}
				this.$router.go(-1)
			},
			getCityList(){
				let urlInfo = this.urlParams()
				let info = {
					userinfo : {
						uid   : urlInfo.uid   || '',
						token : urlInfo.token || ''
					}
				}
				if(!this.isWeChat){
					info.flag = 'wechat'
				}
				this.$axiosPost('/api/Store/getCity',{
					data : JSON.stringify(info)
				}).then( res => {
					if(res){
						this.cityList  = res
						for(let item in this.cityList){
							for(let items in this.cityList[item]){
								if(items === getUrlParam('city')){
									this.cityName = this.cityList[item][items]
								}
							}
						}
						this.getCityName(res)
					}
				})
			},
			weChatGetCity(){
				if(getCookie('cityname') || getCookie('cityid')){
					return
				}
				this.$axiosGetno('/utils/ip/city.json').then( res => {
					if(res.code === 200){
						this.cityName = res.data.city
						setCookie('cityname',this.cityName,30)
						setCookie('cityid',res.data.city_id,30)
					}
				})
			},
			getShopList(page,city){
				let currentCity
				if(city){
					currentCity = city
					setCookie('cityid',currentCity,30)
				}else{
					currentCity = getUrlParam('city')
					setCookie('cityid',currentCity,30)
				}
				if(this.hasPage){
					return
				}
				this.$vux.loading.show({
					 text: '加载中'
				})
				this.$axiosGet('/mall/stores/findbygeo.json',
					{
						uid   : getUrlParam('uid')   || getCookie('uid'),
						token : getUrlParam('token') || getCookie('token'),
						page  : page,
						latitude  : getUrlParam('latitude')  || this.locations.latitude,
						longitude : getUrlParam('longitude') || this.locations.longitude,
						key       : this.keyword,
						cityid	  : currentCity,
						pageSize  : 20,
						isclaim   : 1
					},true				
				).then( res => {
					this.$vux.loading.hide()
					if(res.code === 200 && page === 1){
						this.noStore = false
						this.storeList = res.data					
					}									
					if(page > 1 && res.code === 200){
						this.noStore = false
						res.data.forEach( item => {
							this.storeList.push(item)
						})
					}
					if(res.code === 404 && page > 1){
						this.noStore = false
						this.dataInfo = res.msg
						this.hasPage = true
						this.$vux.toast.text(res.msg || '数据加载异常','top')
					}
					if(res.code === 404 && page === 1){
						this.storeList = []
						this.noStore = true
						this.$vux.toast.text(res.msg || '该地区暂无数据','top')
					}
				})
			},
			//跳转到认领页面
			goClaim(item){
				localStorage.setItem('avatar',JSON.stringify(item))
				this.param = 'setting'
				//分享店铺
				if(this.isShare == 1){
					this.$router.push({path:'/shareDetail',query:{shop_id:item.shop_id,cat_pid:14705}})
					return
				}
				//认领店铺
				let urlInfo = this.urlParams()
				if(!urlInfo){
					return
				}
				item.cityName = this.cityName
				let statuinfo = {
					userinfo  : {
						uid   : urlInfo.uid   || '',
						token : urlInfo.token || ''
					},
					shop_id   : item.shop_id
				}
				this.$axiosPost('/api/Store/getStatus',{
					data : JSON.stringify(statuinfo)
				}).then( res =>{					
//					let fuid = getUrlParam('fuid') || ''
//					if((fuid && fuid != '0') && res.status){
//						this.$router.push({path:'./relevance',query:{type:'entity',cityId:getCookie('cityid')}})
//						return
//					}
					if(res.status === 0 || res.status === -1){
						this.$vux.alert.show({
							title: '提醒',
        					content: '你已认领过此店，请耐心等待结果',
						})
						//this.$router.push({path:'/examine',query:{status:res.status,fromin:'entity'}})
					}else if(res.status){
						this.$router.push({path:'/setting',query:{cityId:getCookie('cityid')}})
					}
				})
				
			},
			submitKey(e){
				e.preventDefault()
				this.getShopList(1,getCookie('cityid'))
			},
			toCreate(){
				this.param = 'create'
				let info = this.urlParams()
				if(info.uid || info.token){
					this.$router.push({path:'/createStore',query:{}})
				}				
			},
			handleCityShow(){
				this.cityShow = true
				setTimeout( ()=> {
					this.$refs.children.scrollRefresh()
				},300)
			},
			closeCity(){
				this.cityShow = false
			},
			closeCityT(city){
				setCookie('cityid',city.id,30)
				this.cityName = city.name
				this.cityShow = false
			},
			getCityName(citys){
				for(let item in citys){
					for(let items in citys[item]){
						if(items === getCookie('cityid')){
							this.cityName = citys[item][items]
							setCookie('cityname',this.cityName,30)
						}
					}
				}
			},
			isWeiXin(){
				let agent = navigator.userAgent.toLowerCase();
			    if (agent.match(/MicroMessenger/i) == "micromessenger") {	
			    	this.weChatGetCity()
			    	this.getLongitude()			    	
			       	this.isWeChat = false
			       	document.getElementById('shop-content').style.top = 0
			    } else {
			    	let cityid = getCookie('cityid') || getUrlParam('city')
					if(!getCookie('cityid')){
						setCookie('cityid')
					}
					this.getShopList(this.page,cityid)
			        this.isWeChat = true
			    }
			}
		},
		watch:{
			cityName(){
				this.page = 1
				this.getShopList(1,getCookie('cityid'))
			}
		},
		filters:{
			juli(value){
				value = value.replace(/,/g,'')
				if(Number(value) < 1){
					return Number(value * 1000) + '米'
				}
				return Number(value).toFixed(2) + '公里'
			}
		},
		computed:{
			moreData(){
				if(this.keyword){
					return false
				}
				if(this.storeList){
					return this.storeList.length >= 10
				}				
			}	
		},
		mounted(){
			document.title ='选择店铺'
			//判断是认领还是分享
			this.isShare = this.$route.query.share || 0
			//this.claimStatus = getCookie('claimSt')
			setTimeout(function(){
				document.getElementById('shop-content').style.bottom = 0
			},200)	
			this.getCityList()
			this.isWeiXin()					
			this.Bscroll = new Bscroll(this.$refs.shops,{
				click:true,
				probeType : 3,
				pullUpLoad: {
				  	threshold: -50
				}
			})
			//上拉加载更多
			this.Bscroll.on('pullingUp', () => {
				this.getShopList(++this.page,getCookie('cityid'))	
				this.Bscroll.finishPullUp()   
				this.Bscroll.refresh()		  
			})
			
		},
		components:{
			CityList,
			Login
		}
	}
</script>

<style lang="less" scoped>
	@import '~styles/mixin.less';
	@import '~vux/src/styles/1px.less';
	.shop{
		text-align: left;
		background: #fff;
		.header-bar{
			position:relative;
			height:1.44rem;
			line-height:2rem;
			text-align:center;
			font-size:.34rem;
			background:#f7f7f8;
			color:#000;
			.iphonex;
			.iconfont{
				position: absolute;
				left: 0;
				top: .54rem;
				height: .9rem;
				line-height: .9rem;
				padding: 0 .2rem;
			}
		}
		.content{
			overflow: hidden;
			position: absolute;
			top: 0rem;
			left: 0;
			right: 0;	
			background: #fff;
			.header{
				display: flex;
				height: .9rem;
				line-height: .9rem;
				background: #f0eff5;
				.address{
					width: 1.5rem;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					text-align: center;
				}
				.ipt-warrp{
					position: relative;
					flex: 1;
					.iconfont{
						position: absolute;
						top: 0;
						left: .1rem;
					}
					input{
						width: 90%;
						padding-left: .5rem;
						height: .55rem;
						border: none;
						border-radius: .1rem;
					}
				}
			}
			.content-item{
				margin-left:.2rem;
				position: relative;
				overflow: hidden;
				display: flex;
				padding:.25rem 0;				
				.img-warrp{
					flex: 0 0 1.2rem;
					width: 1.2rem;
					height: 1.2rem;				
					.item-img{
						width: 100%;
						height: 100%;
					}
				}
				.item-info{
					flex: 1;
					overflow: hidden;
					margin-left: .2rem;
					display: flex;
					flex-direction: column;
					justify-content: center;
					.item-title{
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						line-height: .5rem;
					}
					.desc{
						overflow: hidden;
						text-overflow: ellipsis;
						height: .64rem;
						font-size: .24rem;
						color: #a3a3a3;
					}
				}
				.item-btn{
					flex: 0 0 1.3rem;
					margin-right: .2rem;
					width: 1.3rem;
					.btn{					
						padding: .05rem 0;
						text-align: center;
						border: 1px solid #f96800;
						color: #f96800;
						border-radius: .06rem;
					}
					.distance{
						white-space: nowrap;
						line-height: .6rem;
						text-align: right;
						font-size: .24rem;
					}
					.claim-ok{
						position: absolute;
						right: -.5rem;
						width: 1.7rem;
						transform: rotate(45deg);
						text-align: center;
						background: #78ca06;
						color: #fff;
						font-size: .12rem;
					}
				}
			}
			.bottom-bar{
				height: .75rem;
				line-height: .75rem;
				text-align: center;
			}
		}
		.no-store{
			margin: 0 auto;
			height: 3.8rem;
			width: 4rem;
			.no-img{
				margin: 0 auto;
				margin-top: .8rem;
				height: 1.5rem;
				width: 1.5rem;
			}
			.desc{
				text-align: center;
				color: #cbcbcb;
			}
			.btn{
				margin: .3rem auto;
				width: 2rem;
				height: .8rem;
				line-height: .8rem;
				text-align: center;
				color: #fff;
				background: #ff1351;
				border-radius: .1rem;
			}
		}
		.fade-enter-active,.fade-leave-active{
			transition: opacity .4s ease-out;
		}
		.fade-enter,.fade-leave-to{
			opacity: 0;
		}
	}
</style>